package com.gpslw.mvc.config;

import com.gpslw.mvc.bean.SexEnum;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

@Configuration
public class MvcConfig implements WebMvcConfigurer, InitializingBean {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new Formatter<LocalDate>() {
            @Override
            public String print(LocalDate localDate, Locale locale) {
                return localDate.format(dateTimeFormatter);
            }

            @Override
            public LocalDate parse(String s, Locale locale) throws ParseException {
                return LocalDate.parse(s, dateTimeFormatter);
            }
        });
        registry.addFormatter(new Formatter<SexEnum>() {
            @Override
            public String print(SexEnum sexEnum, Locale locale) {
                return sexEnum.toString();
            }

            @Override
            public SexEnum parse(String s, Locale locale) throws ParseException {
                Integer code = Integer.valueOf(s);
                SexEnum sexByCode = SexEnum.getSexByCode(code);
                return sexByCode;
            }
        });
    }

    @PostConstruct
    public void postConstruct(){
        System.out.println("this is postConstract");
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("this is afterPropertiesSet");
    }
}
